extends Node2D

var level = 0
var card = preload("res://scenes/card.tscn")
var plant = preload("res://scenes/plant.tscn")
var zombie = preload("res://scenes/zombie.tscn")
var sunshine =preload("res://scenes/sunshine.tscn")
var data
var stored_file = "res://save/init.json"
var ibar = 0
var selected_cards = []
var number = 50
var virtual_plant = false
var available_cards = []
var started = false
var field_start_x = 250
var field_start_y = 80
var field_end_x = 970
var field_end_y = 570
var field_slice_width = (field_end_x-field_start_x)/9
var field_slice_height = (field_end_y-field_start_y)/5
var time = 0

var settled_plants = [
	[0,0,0,0,0,0,0,0,0],
	[0,0,0,0,0,0,0,0,0],
	[0,0,0,0,0,0,0,0,0],
	[0,0,0,0,0,0,0,0,0],
	[0,0,0,0,0,0,0,0,0]
]
var field_slices = []

var zombie_show_rows = [0,0,0,0,0]

var plants = [[],[],[],[],[]]

func calc_field_slices():
	for row in range(len(settled_plants)):
		field_slices.append([])
		for col in range(len(settled_plants[0])):
			field_slices[-1].append([Vector2(field_start_x+field_slice_width*col,
											field_start_y+field_slice_height*row),
									Vector2(field_start_x+field_slice_width*(col+1),
											field_start_y+field_slice_height*(row+1))])
			
func get_random_zombie_position(row) -> Vector2:
	var y = field_start_y + (row + 0.5) * field_slice_height - 20
	return Vector2(1100,y)

func _ready() -> void:
	data = load_data()
	var cur_x = 350
	var cur_y = 130
	calc_field_slices()
	for card_type in data["available_cards"]:
		var new_card = card.instantiate()
		new_card.selected_type = card_type
		new_card.position = Vector2(cur_x,cur_y)
		new_card.level = self
		available_cards.append(new_card)
		add_child(new_card)
		cur_x += 50

func _physics_process(delta):
	pass
	
func copy_to_bar(card_type,position) -> void:
	if card_type in selected_cards:
		return
	var new_card = card.instantiate()
	var tween = create_tween()
	var target_position = Vector2(ibar*50+350,10)  # 在编辑器中设置目标位置
	var slide_duration = 0.6
	new_card.selected_type = card_type
	new_card.position = position
	new_card.state = new_card.State.BAR
	new_card.level = self
	selected_cards.append(card_type)
	add_child(new_card)
	ibar += 1
	tween.tween_property(new_card, "position", target_position, slide_duration)\
		 .set_trans(Tween.TRANS_QUAD).set_ease(Tween.EASE_OUT)

func copy_to_ground(card_type,position) -> void:
	if started:
		var new_plant = plant.instantiate()
		new_plant.position = position
		new_plant.level = self
		new_plant.selected_type = card_type
		new_plant.show_moving_anim()
		add_child(new_plant)
		var shadow_plant = new_plant.duplicate()
		shadow_plant.is_shadow = true
		shadow_plant.level = self
		shadow_plant.modulate.a = 0.5
		shadow_plant.selected_type = card_type
		new_plant.show_moving_anim()
		add_child(shadow_plant)

func calc_shadow_position(position:Vector2) -> Vector2i:
	for row in range(5):
		for col in range(9):
			if position.x > field_slices[row][col][0].x and \
				position.x < field_slices[row][col][1].x and \
				position.y > field_slices[row][col][0].y and \
				position.y < field_slices[row][col][1].y:
				return Vector2i(row,col)
	return Vector2i(0,0)

func remove_plant(field_slice):
	remove_child(settled_plants[field_slice.x][field_slice.y])
	settled_plants[field_slice.x][field_slice.y].queue_free()
	settled_plants[field_slice.x][field_slice.y] = 0
	
	

func append_plant(field_slice,plant):
	settled_plants[field_slice.x][field_slice.y] = plant
	attack()
	
func save_data():
	
	var json_string = JSON.stringify(data, "\t")  # 使用\t缩进美化格式
	
	# 打开文件写入
	var file = FileAccess.open(stored_file, FileAccess.WRITE)
	if file == null:
		var error = FileAccess.get_open_error()
		push_error("无法打开文件写入: %s (错误代码: %d)" % [stored_file, error])
		return false
	
	# 写入内容并关闭文件
	file.store_string(json_string) 
	file.close()
	return true

func load_data() -> Dictionary:
	# 检查文件是否存在
	if not FileAccess.file_exists(stored_file):
		push_error("文件不存在: " + stored_file)
		return {}
	
	# 打开文件读取
	var file = FileAccess.open(stored_file, FileAccess.READ)
	if file == null:
		var error = FileAccess.get_open_error()
		push_error("无法打开文件读取: %s (错误代码: %d)" % [stored_file, error])
		return {}
	
	# 读取内容并解析JSON
	var json_string = file.get_as_text()
	file.close() 
	
	var json = JSON.new()
	var parse_result = json.parse(json_string)
	if parse_result != OK:
		push_error("JSON解析错误: %s (行 %d)" % [json.get_error_message(), json.get_error_line()])
		return {}
	
	return json.get_data()


func _on_start_btn_pressed() -> void:
	for card in available_cards:
		card.visible = false
	$dock.visible = false
	$start_btn.visible = false
	started = true

func attack():
	for row in range(5):
		if zombie_show_rows[row] > 0:
			for col in range(9):
				if settled_plants[row][col]:
					settled_plants[row][col].start_attack()
				
func stop_attack():
	for row in range(5):
		if zombie_show_rows[row] == 0:
			for col in range(9):
				if settled_plants[row][col]:
					settled_plants[row][col].stop_attack()

func _on_timer_timeout() -> void:
	time += 1
	if time % 5 == 0 and time > 10:
		var new_zombie = zombie.instantiate()
		if time % 10 == 0:
			new_zombie.selected_type = "conehead"
			print("conhead")
		else:
			new_zombie.selected_type = "normal"
			print("normal")
		var random_row = randi()%5
		new_zombie.position = get_random_zombie_position(random_row)
		zombie_show_rows[random_row] += 1
		new_zombie.row = random_row
		new_zombie.level = self
		add_child(new_zombie)
		attack()
	if time % 3 == 0 and time > 7:
		var new_sunshine = sunshine.instantiate()
		new_sunshine.position = Vector2(501,21) 
		add_child(new_sunshine)
		
func zombie_die(row):
	zombie_show_rows[row] -= 1
	stop_attack()
